import { defineStore } from "pinia";
import { get, isEmpty } from "lodash-es";
import { UserInfo } from "@/types/store/user.store";
import { RoleEnum } from "@/enums/roleEnum";
import type { LoginInfo, LoginParams } from "@/types/model/user.model";
import { getUserInfo, loginApi, logoutApi } from "@/api/sys/user.api";
import { getUserOwnBranch } from "@/api/branches/branches.api";
import { AuthStorage } from "@/storage/auth.storage";
import { TenantStorage } from "@/storage/tenant.storage";
import { RoleStorage } from "@/storage/role.storage";
import { AppStorage } from "@/storage/app.storage";
import { DictStorage } from "@/storage/dict.storage";
import { router } from "@/router";
import { CHOOSE_BRANCH_PAGE } from "@/router/routerNames";
import { USER_STORE } from "../modulesName";

interface UserState {
  userInfo: Nullable<UserInfo>;
  currentBranch: any;
  token?: string;
  roleList: RoleEnum[];
  dictItems?: [];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
  tenantid?: string | number;
  shareTenantId?: Nullable<string | number>;
  loginInfo?: Nullable<LoginInfo>;
  ownBranches?: any[];
}

export const useUserStore = defineStore({
  id: USER_STORE,
  state: (): UserState => {
    return {
      // 用户信息
      userInfo: null,
      // 登录门店
      currentBranch: null,
      // token
      token: undefined,
      // 角色列表
      roleList: [],
      // 字典
      dictItems: [],
      // session过期时间
      sessionTimeout: false,
      // Last fetch time
      lastUpdateTime: 0,
      //租户id
      tenantid: "",
      // 分享租户ID
      // 用于分享页面所属租户与当前用户登录租户不一致的情况
      shareTenantId: null,
      //登录返回信息
      loginInfo: null,
      // 可以管控的门店列表
      ownBranches: [],
    };
  },
  getters: {
    getToken(): string {
      return this.token || AuthStorage.getAuthToken();
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getCurrentBranchName(): string {
      return get(this.currentBranch, "name") || "/";
    },
    getRoleList(): RoleEnum[] {
      return this.roleList.length > 0
        ? this.roleList
        : RoleStorage.getRoleList();
    },
  },
  actions: {
    /**
     * 初始化
     */
    init() {
      console.log("==== APP INIT ====");
      const authToken = AuthStorage.getAuthToken();
      const loginInfo = AuthStorage.getLoginInfo();
      const userInfo = AppStorage.getUserInfo();
      if (authToken && !isEmpty(loginInfo) && !isEmpty(userInfo)) {
        const dictItems = DictStorage.getDictList();
        const currentBranch = AuthStorage.getCurrentBranch();
        const roleList = RoleStorage.getRoleList();
        const ownBranches = AuthStorage.getOwnBranches();
        
        this.token = authToken;
        this.loginInfo = loginInfo;
        this.userInfo = userInfo as UserInfo;
        this.dictItems = dictItems;
        this.currentBranch = currentBranch;
        this.roleList = roleList;
        this.ownBranches = ownBranches;
      }
    },
    changeCurrentBranch(branch: any) {
      this.currentBranch = branch;
      AuthStorage.setCurrentBranch(branch);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    setToken(info: string | undefined) {
      this.token = info ? info : "";
      AuthStorage.setAuthToken(info as string);
    },
    setLoginInfo(info: LoginInfo | null) {
      this.loginInfo = info;
      AuthStorage.setLoginInfo(info);
    },
    setTenant(id: string) {
      this.tenantid = id;
      TenantStorage.setAuthTenant(id);
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList;
      RoleStorage.setRoleList(roleList);
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      AppStorage.setUserInfo(info);
    },
    setAllDictItems(dictItems: any) {
      this.dictItems = dictItems;
      DictStorage.setDictList(dictItems);
    },
    async handleGetUserOwnBranch() {
      const res = await getUserOwnBranch();
      this.ownBranches = get(res, "result") || [];
      AuthStorage.setOwnBranches(this.ownBranches);
    },
    async getUserInfoAction() {
      if (!this.getToken) {
        return null;
      }
      const data = await getUserInfo();
      await this.handleGetUserOwnBranch();
      const userInfo = get(data, "result.userInfo") as any;
      if (userInfo) {
        const { roles = [] } = userInfo;
        if (Array.isArray(roles)) {
          const roleList = roles.map((item: any) => item.value) as RoleEnum[];
          this.setRoleList(roleList);
        } else {
          userInfo.roles = [];
          this.setRoleList([]);
        }
        this.setUserInfo(userInfo);
      }

      const sysAllDictItems = get(data, "result.sysAllDictItems");
      if (sysAllDictItems) {
        this.setAllDictItems(sysAllDictItems);
      }
      return userInfo;
    },
    clearAll() {
      window.localStorage.clear();
      this.userInfo = null;
      this.currentBranch = null;
      this.token = undefined;
      this.roleList = [];
      this.dictItems = [];
      this.sessionTimeout = false;
      this.lastUpdateTime = 0;
      this.tenantid = "";
      this.shareTenantId = null;
      this.loginInfo = null;
      this.ownBranches = [];
    },
    async logout() {
      await logoutApi();
      this.clearAll();
    },
    async login(
      params: LoginParams & {
        goHome?: boolean;
      }
    ) {
      const { goHome = true, ...loginParams } = params;
      try {
        const data = await loginApi(loginParams);

        const token = get(data, "result.token");
        const loginTenantId = get(data, "result.userInfo.loginTenantId");
        this.setToken(token);
        this.setTenant(loginTenantId);
        return this.afterLoginAction(goHome, data.result);
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async afterLoginAction(goHome?: boolean, data?: any): Promise<any> {
      if (!this.getToken) {
        return null;
      }
      // 获取用户信息
      const userInfo = await this.getUserInfoAction();
      console.log(userInfo);
      const sessionTimeout = this.sessionTimeout;
      if (sessionTimeout) {
        this.setSessionTimeout(false);
      } else {
        await this.setLoginInfo({ ...data, isLogin: true });
        let redirect = router.currentRoute.value?.query?.redirect as string;
        // if (redirect && goHome) {
        //   await router.replace(redirect);
        //   return data;
        // }

        // if (goHome) {
        //   let path = get(userInfo, "homePath") || "/dashboard";
        //   await router.replace(path);
        // }

        let targetUrl = CHOOSE_BRANCH_PAGE.URL;
        if (redirect) {
          targetUrl += `?redirect=${redirect}`;
        }

        await router.replace(targetUrl);
      }
      return data;
    },
  },
});
